/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.finance.ar.memo.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.redragon.framework.hibernate.data.SnowFlake;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.springmvc.ControllerSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.erp.dataset.service.DatasetCommonService;
import com.erp.finance.ar.invoice.dao.model.ArInvoiceLine;
import com.erp.finance.ar.invoice.dao.model.ArInvoiceLineCO;
import com.erp.finance.ar.invoice.service.ArInvoiceLineService;
import com.erp.finance.ar.memo.dao.model.ArInvoiceMemoLine;
import com.erp.finance.ar.memo.dao.model.ArInvoiceMemoLineBase;
import com.erp.finance.ar.memo.dao.model.ArInvoiceMemoLineCO;
import com.erp.finance.ar.memo.service.ArInvoiceMemoLineService;
import com.erp.finance.areco.memo.dao.model.ArInvoiceMemoLineM;
import com.erp.finance.areco.memo.service.ArInvoiceMemoLineMService;
import com.erp.inv.output.service.InvOutputLineService;
import com.erp.masterdata.common.service.MasterDataCommonService;
import com.erp.order.so.dao.model.SoLine;
import com.erp.order.so.service.SoLineService;

@Controller
@RequestMapping("/web/arInvoiceMemoLine")
public class ArInvoiceMemoLineWebController extends ControllerSupport{
    
    //日志处理
    private Logger logger = LoggerFactory.getLogger(ArInvoiceMemoLineWebController.class);
    
    //服务层注入
    @Autowired
    private ArInvoiceMemoLineService arInvoiceMemoLineService;
    @Autowired
    private ArInvoiceLineService arInvoiceLineService;
    @Autowired
    private MasterDataCommonService masterDataCommonService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    private SoLineService soLineService;
    @Autowired
    private InvOutputLineService invOutputLineService;
    @Autowired
    private ArInvoiceMemoLineMService arInvoiceMemoLineMService;
    
    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getArInvoiceMemoLineList");
    }
    
    
    
    /**
     * 
     * @description 查询数据列表
     * @date 2020-10-27 14:37:08
     * @author 
     * @param pages
     * @param arInvoiceMemoLineCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getArInvoiceMemoLineList")
    public String getArInvoiceMemoLineList(Pages pages, ArInvoiceMemoLineCO arInvoiceMemoLineCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        pages.setMax(100);
        
        //物料
        Map materialMap = this.masterDataCommonService.getMaterialMap();
        //物料单位
        Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
        
        //分页查询数据
        List<ArInvoiceMemoLineBase> lineList = new ArrayList<ArInvoiceMemoLineBase>();
        //根据version请求参数，判断数据从原表获取还是变更表获取
        if(arInvoiceMemoLineCO.getVersion()!=null&&arInvoiceMemoLineCO.getVersion()>0) {
            ArInvoiceMemoLineM arInvoiceMemoLineM = new ArInvoiceMemoLineM();
            arInvoiceMemoLineM.setInvoiceHeadCode(arInvoiceMemoLineCO.getInvoiceHeadCode());
            arInvoiceMemoLineM.setVersion(arInvoiceMemoLineCO.getVersion());
            List<ArInvoiceMemoLineM> list = this.arInvoiceMemoLineMService.getDataObjects(pages, arInvoiceMemoLineM);
            for(ArInvoiceMemoLineM obj: list) {
                lineList.add(obj);
            }
        }else {
            List<ArInvoiceMemoLine> list = this.arInvoiceMemoLineService.getArInvoiceMemoLineListByHeadCode(pages, arInvoiceMemoLineCO);
            for(ArInvoiceMemoLine obj: list) {
                lineList.add(obj);
            }
        }
        
        for(ArInvoiceMemoLineBase line: lineList) {
            //获取发票信息
            ArInvoiceLine arInvoiceLine = this.arInvoiceLineService.getDataObject(line.getInvoiceSourceLineCode());
            
            SoLine soLine = this.soLineService.getDataObject(arInvoiceLine.getInvoiceSourceLineCode());
            line.setMaterialCode(soLine.getMaterialCode());
            line.setMaterialName(materialMap.get(soLine.getMaterialCode()).toString());
            line.setStandard(this.masterDataCommonService.getMdMaterialInfoCache(soLine.getMaterialCode()).getStandard());
            line.setPrice(soLine.getPrice());
            line.setUnit(materialUnitMap.get(soLine.getUnit()).toString());
            line.setSoLineAmount(arInvoiceLine.getAmount());
        }
        
        //页面属性设置
        model.addAttribute("receiptLineList", lineList);
        model.addAttribute("pages", pages);
        
        return "arInvoiceMemo/tab/arInvoiceMemoLineTab";
    }
    
    
    
    /**
     * 
     * @description 获取销售订单选择框
     * @date 2020年7月20日
     * @author dongbin
     * @return
     * @return String
     *
     */
    @RequestMapping("getSelectInvoiceLineModal")
    public String getSelectInvoiceLineModal(Pages pages, String soInvoiceHeadCode, ArInvoiceLineCO receiptLineCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        pages.setMax(1000);
        
        //分页查询销售发票行数据
        List<ArInvoiceLine> arInvoiceLineList = this.arInvoiceLineService.getArInvoiceLineListByHeadCode(soInvoiceHeadCode);
        
        //获取发票行数据
        List<ArInvoiceMemoLine> arInvoiceMemoLineList = this.arInvoiceMemoLineService.getArInvoiceMemoLineListByHeadCode(receiptLineCO.getInvoiceHeadCode());
        
        //剔除已经做了发票行的销售订单行
        Iterator<ArInvoiceLine> arInvoiceLineIt = arInvoiceLineList.iterator();
        while(arInvoiceLineIt.hasNext()) {
            ArInvoiceLine arInvoiceLineItTemp = arInvoiceLineIt.next();
            for(ArInvoiceMemoLine arInvoiceMemoLineTemp: arInvoiceMemoLineList) {
                if(arInvoiceLineItTemp.getInvoiceLineCode().equals(arInvoiceMemoLineTemp.getInvoiceSourceLineCode())) {
                    arInvoiceLineIt.remove();
                    break;
                }
            }
        }
        //重置总数据数量
        pages.setDataNumber(arInvoiceLineList.size());
        
        //循环设置订单行相关信息
        for(ArInvoiceLine arInvoiceLineTemp: arInvoiceLineList) {
            SoLine soLine = this.soLineService.getDataObject(arInvoiceLineTemp.getInvoiceSourceLineCode());
            arInvoiceLineTemp.setMaterialCode(soLine.getMaterialCode());
            arInvoiceLineTemp.setPrice(soLine.getPrice());
            arInvoiceLineTemp.setUnit(soLine.getUnit());
        }
        
        //物料
        Map materialMap = this.masterDataCommonService.getMaterialMap();
        //物料单位
        Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
        
        //页面属性设置
        model.addAttribute("lineList", arInvoiceLineList);
        model.addAttribute("pages", pages);
        model.addAttribute("materialMap", materialMap);
        model.addAttribute("materialUnitMap", materialUnitMap);
        
        return "arInvoiceMemo/pop/selectInvoiceLineModal";
    }
    
    
    
    /**
     * 
     * @description 查询单条数据
     * @date 2020-10-27 14:37:08
     * @author 
     * @param arInvoiceMemoLine
     * @param model
     * @return String
     *
     */
    @RequestMapping("getArInvoiceMemoLine")
    public String getArInvoiceMemoLine(ArInvoiceMemoLine arInvoiceMemoLine, String invoiceSourceType, Model model) {
        //查询要编辑的数据
        if(arInvoiceMemoLine!=null&&arInvoiceMemoLine.getInvoiceLineId()!=null) {
            arInvoiceMemoLine = this.arInvoiceMemoLineService.getDataObject(arInvoiceMemoLine.getInvoiceLineId());
            //根据来源获取单据数据
            if(StringUtils.isNotBlank(invoiceSourceType)) {
                //物料
                Map materialMap = this.masterDataCommonService.getMaterialMap();
                //物料单位
                Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
                
                //获取发票信息
                ArInvoiceLine arInvoiceLine = this.arInvoiceLineService.getDataObject(arInvoiceMemoLine.getInvoiceSourceLineCode());
                arInvoiceMemoLine.setInvoiceQuantity(arInvoiceLine.getQuantity());
                arInvoiceMemoLine.setSoLineAmount(arInvoiceLine.getAmount());
                //获取订单信息
                SoLine soLine = this.soLineService.getDataObject(arInvoiceLine.getInvoiceSourceLineCode());
                arInvoiceMemoLine.setMaterialCode(soLine.getMaterialCode());
                arInvoiceMemoLine.setMaterialName(materialMap.get(soLine.getMaterialCode()).toString());
                arInvoiceMemoLine.setStandard(this.masterDataCommonService.getMdMaterialInfoCache(soLine.getMaterialCode()).getStandard());
                arInvoiceMemoLine.setPrice(soLine.getPrice());
                arInvoiceMemoLine.setUnit(materialUnitMap.get(soLine.getUnit()).toString());
            }
        }else {
            //根据来源获取单据数据
            /*
            if(StringUtils.isNotBlank(invoiceSourceType)) {
            }
            */
            
            arInvoiceMemoLine.setStandard(this.masterDataCommonService.getMdMaterialInfoCache(arInvoiceMemoLine.getMaterialCode()).getStandard());
        }
        
        //页面属性设置
        model.addAttribute("receiptLine", arInvoiceMemoLine);
        
        return "arInvoiceMemo/pop/addLineModal";
    }
    
    
    
    /**
     * 
     * @description 编辑数据
     * @date 2020-10-27 14:37:08
     * @author 
     * @param arInvoiceMemoLine
     * @param bindingResult
     * @param model
     * @return String
     *
     */
    @RequestMapping("editArInvoiceMemoLine")
    @ResponseBody
    public String editArInvoiceMemoLine(@Valid ArInvoiceMemoLine arInvoiceMemoLine, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        try {
            /*
            //参数校验
            Map<String, String> errorMap = this.validateParameters(bindingResult, model);
            if(errorMap.size()>0) {
                return "forward:getReceiptLine";
            }
            */
            
            //对当前编辑的对象初始化默认的字段
            if(arInvoiceMemoLine.getInvoiceLineId()==null) {
                arInvoiceMemoLine.setInvoiceLineCode(SnowFlake.getConcurrentId().toString());
            }
            
            //保存编辑的数据
            this.arInvoiceMemoLineService.insertOrUpdateDataObject(arInvoiceMemoLine);
            
            return "{\"result\":\"success\"}";
        }catch(Exception e) {
            return "{\"result\":\"error\"}";
        }
    }
    
    
    
    /**
     * 
     * @description 删除数据
     * @date 2020-10-27 14:37:08
     * @author 
     * @param arInvoiceMemoLine
     * @return String
     *
     */
    @RequestMapping("deleteArInvoiceMemoLine")
    @ResponseBody
    public String deleteArInvoiceMemoLine(ArInvoiceMemoLine arInvoiceMemoLine, RedirectAttributes attr) {
        try {
            //删除数据前验证数据
            if(arInvoiceMemoLine!=null&&arInvoiceMemoLine.getInvoiceLineId()!=null) {
                //删除数据
                this.arInvoiceMemoLineService.deleteDataObject(arInvoiceMemoLine);
            }
            
            return "{\"result\":\"success\"}";
        }catch(Exception e) {
            return "{\"result\":\"error\"}";
        }
    }
}
